package com.vcredit.creditcat.util;

import org.apache.http.Header;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;



/**
 * Created by liaoshengjun on 2017/8/10.
 */
public class HttpRequestExt {
	public static String doPut(String url,String json,String charset,Header[] headers) throws Exception{
		CloseableHttpClient httpClient= HttpClients.createDefault();
		StringEntity entry=new StringEntity(json, charset);
		entry.setContentType("application/json");
		entry.setContentEncoding("utf-8");
		HttpPut put=new HttpPut(url);
		put.setHeaders(headers);
		put.setEntity(entry);
		CloseableHttpResponse response=httpClient.execute(put);
		if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK || response.getStatusLine().getStatusCode() == HttpStatus.SC_BAD_REQUEST){
			return EntityUtils.toString(response.getEntity(), charset);
		}else {
			throw new RuntimeException("http request result code:" + response.getStatusLine().getStatusCode());
		}
	}
	public static String doPost(String url,String json,String charset,Header[] headers) throws Exception{
		CloseableHttpClient httpClient= HttpClients.createDefault();
		HttpPost post = new HttpPost(url);
		StringEntity entry=new StringEntity(json, charset);
		entry.setContentType("application/json");
		entry.setContentEncoding("utf-8");
		post.setHeaders(headers);
		post.setEntity(entry);
		CloseableHttpResponse response=httpClient.execute(post);
		if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK || response.getStatusLine().getStatusCode() == HttpStatus.SC_BAD_REQUEST){
			return EntityUtils.toString(response.getEntity(), charset);
		}else {
			throw new RuntimeException("http request result code:" + response.getStatusLine().getStatusCode());
		}
	}
}
